package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.redisconfig.RedissonAutoConfiguration;
import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.mall.dto.ClearCartItemRequest;
import com.cskaoyan.mall.dto.ClearCartItemResponse;
import com.cskaoyan.shopping.constants.GlobalConstants;
import com.cskaoyan.shopping.converter.CartItemConverter;
import com.cskaoyan.shopping.dal.entitys.Item;
import com.cskaoyan.shopping.dal.persistence.ItemMapper;
import com.cskaoyan.shopping.dto.*;
import com.cskaoyan.shopping.form.CartForm;
import com.cskaoyan.shopping.service.ICartService;
import com.cskaoyan.user.constants.UserRetCode;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

/**
 * @auther cskaoyan
 * @date 2022/6/16:16:34
 */
@Service
public class ICartSeviceImpl implements ICartService {

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    CartItemConverter cartItemConverter;

    /**
     * 获取购物车所有的商品
     *
     * @param
     * @return
     * @author D_y_Y
     * @since 2022/06/19 16:46
     */
    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        String uid = request.getUserId().toString();
        RMap<String, CartProductDto> map = redissonClient.getMap(GlobalConstants.CARTS_OF_USER + uid);
        CartListByIdResponse cartListByIdResponse = new CartListByIdResponse();
        if (map.size() == 0) {
            cartListByIdResponse.setCartProductDtos(null);
        } else {
            List<CartProductDto> cartProductDtos = new LinkedList<>();
            cartProductDtos.addAll(map.values());
            cartListByIdResponse.setCartProductDtos(cartProductDtos);

        }

        cartListByIdResponse.setCode(UserRetCode.SUCCESS.getCode());
        cartListByIdResponse.setMsg(UserRetCode.SUCCESS.getMessage());
        return cartListByIdResponse;
    }
    //List<CartProductDto>

    /**
     * 添加购物车
     *
     * @param
     * @return
     * @author D_y_Y
     * @since 2022/06/19 16:42
     */
    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        AddCartResponse addCartResponse = new AddCartResponse();
        String uid = request.getUserId().toString();
        //拿到redis中缓存的购物车清单
        RMap<String, CartProductDto> map = redissonClient.getMap(GlobalConstants.CARTS_OF_USER + uid);
        //查看购物车清单中是否存在该商品
        CartProductDto product = (CartProductDto) map.get(request.getItemId().toString());
        if (product != null) {
            product.setProductNum(product.getProductNum() + request.getNum());
            map.put(request.getItemId().toString(), product);
            addCartResponse.setCode(UserRetCode.SUCCESS.getCode());
            addCartResponse.setMsg(UserRetCode.SUCCESS.getMessage());
            return addCartResponse;
        }
        //
        Item item = itemMapper.selectByPrimaryKey(request.getItemId());
        //将商品转化购物车对象
        CartProductDto cartProductDto = CartItemConverter.item2Dto(item);

        cartProductDto.setProductNum(request.getNum().longValue());
        cartProductDto.setChecked(GlobalConstants.CARTS_OF_TRUE);

        //添加入redis

        map.put(request.getItemId().toString(), cartProductDto);

        addCartResponse.setCode(UserRetCode.SUCCESS.getCode());
        addCartResponse.setMsg(UserRetCode.SUCCESS.getMessage());
        return addCartResponse;

    }

    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        return null;
    }

    @Override
    public CheckAllItemResponse checkAllCartItem(CheckAllItemRequest request) {
        request.getChecked();
        //获取全部购物车中信息  对应dto类为CheckAllItemRequest/response
        CheckAllItemResponse response = new CheckAllItemResponse();
        try {
            String userId = request.getUserId().toString();
            //根据userId获取当前用户的购物车  购物车实体类为CartProductDto
            RMap<String, CartProductDto> map = redissonClient.getMap(GlobalConstants.CARTS_OF_USER +userId);
            Set<String> itemIds = map.keySet();
            //获取全部的itemIds 保存到list
            ArrayList<String> list = new ArrayList<>(itemIds);
            for (int i = 0; i < itemIds.size(); i++) {
                String itemId = list.get(i);
                CartProductDto cartProductDto = map.get(itemId);
                //改变对象的checked
                cartProductDto.setChecked(request.getChecked());
                map.put(itemId, cartProductDto);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return response;


    }

    @Override
    public DeleteCartItemResponse deleteCartItem(DeleteCartItemRequest request) {
        //删除购物车中商品  对应dto类为 DeleteCartItemRequest/Response
        request.requestCheck();
        DeleteCartItemResponse deleteCartItemResponse = new DeleteCartItemResponse();
        //获取购物车中信息-从redis中获取
        try {
            String userId = request.getUserId().toString();
            RMap<String, CartProductDto> map = redissonClient.getMap(GlobalConstants.CARTS_OF_USER +userId);
            //删除
            map.remove(request.getItemId().toString());
            deleteCartItemResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            deleteCartItemResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return deleteCartItemResponse;
    }


    @Override
    public DeleteCheckedItemResposne deleteCheckedItem(DeleteCheckedItemRequest request) {
        //删除选中的商品
        request.requestCheck();
        DeleteCheckedItemResposne resposne = new DeleteCheckedItemResposne();
        try {
            String userId = request.getUserId().toString();
            RMap<String, CartProductDto> cartMap = redissonClient.getMap(GlobalConstants.CARTS_OF_USER +userId);

            Set<String> keys = cartMap.keySet();
            for (String key : keys) {
                CartProductDto cartProductDto = ((CartProductDto) cartMap.get(key));
                if (cartProductDto.getChecked().equals("true")) {
                    cartMap.remove(key);
                }
            }
            RMap<String, Object> map = redissonClient.getMap(userId.toString());
            resposne.setCode(SysRetCodeConstants.SUCCESS.getCode());
            resposne.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return resposne;
    }

    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        return null;
    }

    @Override
    public void updateCartCheck(CartForm cartForm) {
        String uid = cartForm.getUserId().toString();
        RMap<String, CartProductDto> map = redissonClient.getMap(GlobalConstants.CARTS_OF_USER + uid);
        CartProductDto cartProductDto = map.get(cartForm.getProductId().toString());
        cartProductDto.setChecked(cartForm.getChecked());
        map.put(cartForm.getProductId().toString(), cartProductDto);

    }
}
